package qeug.shsh.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;

import java.util.Collections;
import java.util.EventObject;
import java.util.Map;

// 付款申请,差旅报销单,费用报销单,预算调整单,资金计划,借款单表单插件：
// 1：费用承担公司初始化带入支付公司；使用单据：付款申请
// 2：费用承担部门初始化带入一级承担部门；使用单据：付款申请,差旅报销单,费用报销单,预算调整单,资金计划,借款单
// 3：分摊明细中一级承担部门赋值逻辑，费用承担部门的部门最上级；使用单据：差旅报销单，费用报销单，付款申请单
public class publicReimburseOrgPlugin extends AbstractFormPlugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        String name = this.getModel().getDataEntityType().getName();
        if ("er_publicreimbursebill".equals(name)) {
            //付款申请单才进入
//            this.getModel().setValue("costcompany", null);//支付公司
            DynamicObject costCompany = (DynamicObject) this.getModel().getValue("costcompany");//费用承担公司
            if (costCompany != null) {
                this.getModel().setValue("qeug_paycompany", costCompany);//支付公司
            }
        }
        DynamicObject costDept = null;
        if ("qeug_fundplan".equals(name) || "qeug_fundadjust".equals(name)) {
            //资金计划，资金计划调整的部门
            costDept = (DynamicObject) this.getModel().getValue("qeug_deparment");//部门
        } else if ("bgm_adjustbill".equals(name)) {
            //预算调整单的部门
            costDept = (DynamicObject) this.getModel().getValue("department");//部门
        } else {
            //付款申请单，差旅报销单，费用报销单，借款单的费用承担部门
            costDept = (DynamicObject) this.getModel().getValue("costdept");//费用承担部门
        }
        if (costDept != null) {
            setCostDept(costDept);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String fieldKey = e.getProperty().getName();
        if ("costdept".equals(fieldKey)) {
            //费用承担部门
            String name = this.getModel().getDataEntityType().getName();
            if ("er_publicreimbursebill".equals(name) || "er_tripreimbursebill".equals(name) || "er_dailyreimbursebill".equals(name) || "er_dailyloanbill".equals(name)) {
                //付款申请单，差旅报销单，费用报销单，借款单才有的费用承担部门，并且只有上面的单据才能进入的逻辑
                ChangeData[] changeSet = e.getChangeSet();
                ChangeData changeData = changeSet[0];
                DynamicObject costDept = (DynamicObject) changeData.getNewValue();//费用承担部门
                if (costDept == null) {
                    return;
                }
                setCostDept(costDept);
            }
        } else if ("qeug_deparment".equals(fieldKey)) {
            //部门
            String name = this.getModel().getDataEntityType().getName();
            if ("qeug_fundplan".equals(name) || "qeug_fundadjust".equals(name)) {
                //资金计划和资金计划调整的部门，并且只有资金计划和资金计划调整才能进入的逻辑
                ChangeData[] changeSet = e.getChangeSet();
                ChangeData changeData = changeSet[0];
                DynamicObject costDept = (DynamicObject) changeData.getNewValue();//费用承担部门
                if (costDept == null) {
                    return;
                }
                setCostDept(costDept);
            }
        } else if ("department".equals(fieldKey)) {
            //部门
            String name = this.getModel().getDataEntityType().getName();
            if ("bgm_adjustbill".equals(name)) {
                //预算调整单的部门，并且只有预算调整单才能进入的逻辑
                ChangeData[] changeSet = e.getChangeSet();
                ChangeData changeData = changeSet[0];
                DynamicObject costDept = (DynamicObject) changeData.getNewValue();//费用承担部门
                if (costDept == null) {
                    return;
                }
                setCostDept(costDept);
            }
        } else if ("entrycostdept_orgrule".equals(fieldKey)) {
            //分摊明细中的费用承担部门:使用的单据：差旅报销单，费用报销单，付款申请单
            String name = this.getModel().getDataEntityType().getName();
            if ("er_publicreimbursebill".equals(name) || "er_tripreimbursebill".equals(name) || "er_dailyreimbursebill".equals(name)) {
                ChangeData[] changeSet = e.getChangeSet();
                ChangeData changeData = changeSet[0];
                DynamicObject costDept = (DynamicObject) changeData.getNewValue();//费用承担部门
                if (costDept == null) {
                    return;
                }
                DynamicObject orgPattern = costDept.getDynamicObject("orgpattern");
                if (orgPattern == null) {
                    return;
                }
                String orgPatternNumber = orgPattern.getString("number");
                if (!orgPatternNumber.equals("Orgform06")) {
                    //填写的费用承担部门的形态不是部门时，直接将费用承担部门值赋值给一级承担部门
                    this.getModel().setValue("qeug_costdeptrule", costDept, changeData.getRowIndex());//一级承担部门
                    return;
                }

                int a = 0;
                DynamicObject cost;
                DynamicObject viewParent = null;
                DynamicObject viewOrg;

                while (true) {
                    if (a == 0) {
                        //第一次进入循环
                        cost = costDept;
                    } else {
                        QFilter[] qFilters = new QFilter[]{
                                new QFilter("number", QCP.equals, viewParent.getString("number"))
                        };
                        cost = BusinessDataServiceHelper.loadSingle("bos_adminorg", qFilters);
                    }
                    long currentOrgId = Long.parseLong(cost.getString("id"));//当前部门ID
                    Map<Long, Long> orgParentMap = OrgUnitServiceHelper.getDirectSuperiorOrg(OrgViewType.Admin, Collections.singletonList(currentOrgId));//获取当前部门的上级组织
                    Long parentId = orgParentMap.get(currentOrgId);//上级组织ID
                    viewParent = BusinessDataServiceHelper.loadSingle("bos_adminorg",
                            new QFilter[]{new QFilter("id", QCP.equals, parentId)});//行政组织-上级组织
                    viewOrg = cost;//组织
                    String viewParentNumber = viewParent.getString("number");
                    QFilter[] qFilters = new QFilter[]{
                            new QFilter("number", QCP.equals, viewParentNumber)
                    };
                    DynamicObject bos_adminOrg = BusinessDataServiceHelper.loadSingle("bos_adminorg", qFilters);//行政组织
                    DynamicObject orgPattern1 = bos_adminOrg.getDynamicObject("orgpattern");//形态
                    String orgPatternNumber1 = orgPattern1.getString("number");
                    if (!orgPatternNumber1.equals("Orgform06")) {
                        //上级不为不为部门的时候，将现在查询的部门赋值给一级承担部门
                        break;
                    } else {
                        a++;
                    }
                }

                DynamicObject bos_adminorg = BusinessDataServiceHelper.loadSingle("bos_adminorg", new QFilter[]{
                        new QFilter("number", QCP.equals, viewOrg.getString("number"))});
                this.getModel().setValue("qeug_costdeptrule", bos_adminorg, changeData.getRowIndex());//一级承担部门
            }
        }
    }

    private void setCostDept(DynamicObject costDept) {
        DynamicObject orgPattern = costDept.getDynamicObject("orgpattern");
        if (orgPattern == null) {
            return;
        }
        String orgPatternNumber = orgPattern.getString("number");
        if (!orgPatternNumber.equals("Orgform06")) {
            //填写的费用承担部门的形态不是部门时，直接将费用承担部门值赋值给一级承担部门
            this.getModel().setValue("qeug_costdept", costDept);//一级承担部门
            return;
        }

        DynamicObject currentOrg = costDept;//当前部门
        DynamicObject topLevelDept = null;//最上级部门

        while (true) {
            long currentOrgId = Long.parseLong(currentOrg.getString("id"));//当前部门ID
            Map<Long, Long> orgParentMap = OrgUnitServiceHelper.getDirectSuperiorOrg(OrgViewType.Admin, Collections.singletonList(currentOrgId));//获取当前部门的上级组织
            Long parentId = orgParentMap.get(currentOrgId);//上级组织ID
            if (parentId == null) {
                // 没有上级组织，当前组织就是最顶级组织
                topLevelDept = currentOrg;
                break;
            }

            DynamicObject parentOrg = BusinessDataServiceHelper.loadSingle("bos_adminorg",
                    new QFilter[]{new QFilter("id", QCP.equals, parentId)});//行政组织-上级组织

            if (parentOrg != null) {
                DynamicObject parentOrgPattern = parentOrg.getDynamicObject("orgpattern");//组织形态
                if (parentOrgPattern != null) {
                    String parentOrgPatternNumber = parentOrgPattern.getString("number");//组织形态编号
                    if (!parentOrgPatternNumber.equals("Orgform06")) {
                        // 上级组织不是部门类型，当前组织即为一级承担部门
                        topLevelDept = currentOrg;
                        break;
                    }
                }
                currentOrg = parentOrg;
            } else {
                // 无法加载上级组织，当前组织为最顶级
                topLevelDept = currentOrg;
                break;
            }
        }

        this.getModel().setValue("qeug_costdept", topLevelDept);//一级承担部门
    }
}
